import request from '@/utils/request.js'
import store from '@/store/index.js'
import router from '@/router/index.js'

// 用户登录接口
export const loginApi = (data) => {
  return request({
    method: "POST",
    url: '/front/user/login',
    data: `phone=${data.phone}&password=${data.password}`
  })
}

// 用户信息接口
export const getUserInfo = () => {
  return request({
    method: "GET",
    url: '/front/user/getInfo'
  })
}

// 退出登录
export const logOut = () => {
  return request({
    method: 'POST',
    url: "/front/user/logout"
  })
}

// 封装 刷新token的接口函数
export const refreshToken = () => {
  return request({
    method: "POST",
    url: '/front/user/refresh_token',
    params: {
      refreshtoken: store.state.tokenInfo.refresh_token
    }
  }).then((res) => {
    // 判断结果为true还是false
    if (res.data.success) {
      // 成功拿到新的 token
      store.commit('changeToken', res.data.content)
    } else {
      // 没有拿到新的 token
      router.push({
        name: 'login'
      })
      throw new Error('刷新token失败！')
    }
  })
}